﻿#include "thread_mutex.h"
#include <errno.h>
#include <stdio.h>
#include <string.h>

int mutex_create(char* errStr, pthread_mutex_t* mtx)
{
    pthread_mutexattr_t  attr;

    int err = pthread_mutexattr_init(&attr);
    if (0 != err)
    {
        sprintf(errStr, 
            "Error on pthread_mutexattr_init, info : %s", 
            strerror(err)
        );

        return -1;
    }

    err = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK);
    if (0 != err) 
    {
        sprintf(errStr,
            "Error on pthread_mutexattr_settype, info : %s",
            strerror(err)
        );

        return -1;
    }

    err = pthread_mutex_init(mtx, &attr);
    if (0 != err) 
    {
        sprintf(errStr,
            "Error on pthread_mutex_init, info : %s",
            strerror(err)
        );

        return -1;
    }
    pthread_mutexattr_destroy(&attr);

    return 0;
}


int mutex_destroy(char* errStr, pthread_mutex_t* mtx)
{
    int err = pthread_mutex_destroy(mtx);

    if (0 != err) 
    {
        sprintf(errStr,
            "Error on pthread_mutex_destroy, info : %s",
            strerror(err)
        );

        return -1;
    }

    return 0;
}


int mutex_lock(char* errStr, pthread_mutex_t* mtx)
{
    int  err = pthread_mutex_lock(mtx);

    if (0 != err)
    {
        sprintf(errStr,
            "Error on pthread_mutex_lock, info : %s",
            strerror(err)
        );

        return -1;
    }

    return 0;
}


int mutex_unlock(char* errStr, pthread_mutex_t* mtx)
{
    int err= pthread_mutex_unlock(mtx);

    if (0 != err)
    {
        sprintf(errStr,
            "Error on pthread_mutex_lock, info : %s",
            strerror(err)
        );

        return -1;
    }

    return 0;
}